package com.itheima.service.impl;

import com.itheima.common.entity.Result;
import com.itheima.file.ExcelUtil;
import com.itheima.mapper.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.IOrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IOrderSettingServiceImpl implements IOrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 文件上传解析并保存至数据库
     *
     * @param excelFile
     * @return
     */
    @Override
    @Transactional
    public Result upload(MultipartFile excelFile) {

        try {
            //最后一天，本月无法设置预约
            if (LocalDate.now().getDayOfMonth() == LocalDate.now().lengthOfMonth()) {
                return Result.of(false, "最后一天，本月无法设置预约!", null);
            }

            String filename = excelFile.getOriginalFilename();
            if (filename == null) {
                return Result.of(false, "文件名不能为空!", null);
            }

            String suffix = filename.substring(filename.lastIndexOf("."));
            if (!".xlsx".equals(suffix) && !".xls".equals(suffix)) {
                return Result.of(false, "文件格式错误!", null);
            }

            InputStream inputStream = excelFile.getInputStream();

            List<List<Object>> listob = null;
            //解析数据
            listob = new ExcelUtil().getBankListByExcel(inputStream, filename);
            inputStream.close();
            List<OrderSetting> orderSettings = new ArrayList<>();

            //遍历封装对象
            for (int i = 0; i < listob.size(); i++) {
                List<Object> row = listob.get(i);

                String col1 = String.valueOf(row.get(0));
                String col2 = String.valueOf(row.get(1));
                if ("".equals(col1) && "".equals(col2)) {
                    continue;
                }
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setOrderDate(col1);
                orderSetting.setNumber(Integer.parseInt(col2));
                orderSettings.add(orderSetting);
                System.out.println(orderSetting);
            }
            //判空
            if (orderSettings.size() == 0) {
                return Result.of(false, "未解析到数据!", null);
            }

            //日期去重
            Set<String> dateString = orderSettings.stream().map(orderSetting -> orderSetting.getOrderDate()).collect(Collectors.toSet());

            if (dateString.size() != orderSettings.size()) {
                return Result.of(false, "日期有重复，请检查规范性!", null);
            }

            //日期信息个数不匹配
            if (dateString.size() != LocalDate.now().lengthOfMonth() - LocalDate.now().getDayOfMonth()) {
                return Result.of(false, "日期信息个数不匹配,请重新下载模板!", null);
            }

            //生成当月当天日到月末的模板
            List<String> currentMonthDateTemplate = generateCurrentMonthDateTemplate();

            //筛选出包含在模板中的数据
            List<String> result = dateString.stream().filter(currentMonthDateTemplate::contains).collect(Collectors.toList());

            if (currentMonthDateTemplate.size() != result.size()) {
                return Result.of(false, "日期信息有误,请重新下载模板!", null);
            }

            //查询数据库中是否存在
            List<OrderSetting> matchOrderSettings = orderSettingDao.getMatchCountByDate(currentMonthDateTemplate.get(0), currentMonthDateTemplate.get(currentMonthDateTemplate.size() - 1));

            if (matchOrderSettings == null || matchOrderSettings.size() == 0) {
                //不存在,添加信息至数据库
                orderSettingDao.add(orderSettings);
            } else {
                //存在,修改数据库信息
                //id,预约人数的原始数据拷贝
                for (int i = 0; i < orderSettings.size(); i++) {
                    OrderSetting orderSetting = orderSettings.get(i);
                    orderSetting.setNumber(Math.max(orderSetting.getNumber(), matchOrderSettings.get(i).getReservations()));
                    orderSetting.setId(matchOrderSettings.get(i).getId());
                    orderSetting.setReservations(matchOrderSettings.get(i).getReservations());
                }

                //删除原有数据
                orderSettingDao.deleteByMatchDate(currentMonthDateTemplate.get(0), currentMonthDateTemplate.get(currentMonthDateTemplate.size() - 1));

                //插入新数据 本质是insert 不是  update
                orderSettingDao.update(orderSettings);
            }

            return Result.of(true, "预约设置成功!", null);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传异常!");
            return Result.of(false, "文件处理异常，请检查文件是否规范!", null);
        }
    }

    /**
     * 生成当月当天日到月末的模板
     *
     * @return
     */
    @Override
    public List<String> generateCurrentMonthDateTemplate() {
        List<String> currentDateString = new ArrayList<>();
        int year = LocalDate.now().getYear();
        String monthValue = String.valueOf(LocalDate.now().getMonthValue());
        if (monthValue.length() == 1) {
            monthValue = "0" + monthValue;
        }
        int lastDay = LocalDate.now().lengthOfMonth();

        for (int day = LocalDate.now().getDayOfMonth() + 1; day <= lastDay; day++) {
            String date = "";
            if (day < 10) {
                date = year + "-" + monthValue + "-0" + day;
            } else {
                date = year + "-" + monthValue + "-" + day;
            }
            currentDateString.add(date);
        }

        System.out.println(currentDateString);
        return currentDateString;
    }

    /**
     * 根据日期修改预约人数
     *
     * @param orderSetting
     * @return
     */
    @Override
    public Result editNumberByOrderDate(OrderSetting orderSetting) {
        String orderDate = orderSetting.getOrderDate();
        int number = orderSetting.getNumber();

        System.out.println(orderDate + "----" + number);
        OrderSetting result = orderSettingDao.getByDate(orderDate);
        if (result == null) {
            //新增
            result = new OrderSetting(orderDate, number);
            orderSettingDao.add(Arrays.asList(result));
        } else {
            //修改
            if (number < result.getReservations()) {
                return Result.of(false, "不得小于已预约人数", null);
            }
            result.setNumber(number);
            orderSettingDao.updateByDate(result);
        }
        return Result.of(true, "预约设置成功", null);
    }

    /**
     * 根据年月查询对应的预约设置信息
     *
     * @param date
     * @return
     */
    @Override
    public Result getOrderSettingByMonth(String date) {
        //分割获取年月
        String[] strings = date.split("-");
        String month = strings[1];
        if (month.length() == 1) {
            month = "0" + month;
        }
        System.out.println(month);
        //查询
        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingByMonth(strings[0], month);
        //结果处理
        orderSettings = orderSettings.stream().map(o -> {
            String orderDate = o.getOrderDate();
            String day = orderDate.substring(orderDate.lastIndexOf("-") + 1);
            o.setOrderDate(day);
            return o;
        }).collect(Collectors.toList());

        return Result.of(true, "获取预约设置数据成功", orderSettings);
    }
}
